package testJdk.thread.countDownLatch;

import testJdk.thread.pool.SinglePoolUtil;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;

/**
 * 测试计数锁
 */
public class CountDownLatchTest {

    public static void main(String[] args) {
        // count值=2
        CountDownLatch latch = new CountDownLatch(2);
        System.out.println("------多任务处理------");
        ExecutorService threadPool = SinglePoolUtil.getThreadPool();
        threadPool.execute(() -> {
            String currentThreadName = Thread.currentThread().getName();
            System.out.println(currentThreadName + ":mike is working");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // count值-1
            latch.countDown();
        });
        threadPool.execute(() -> {
            String currentThreadName = Thread.currentThread().getName();
            System.out.println(currentThreadName + ":jake is working");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // count值-1
            latch.countDown();
        });

        try {
            // 调用await()方法的线程会被挂起，它会等待直到count值为0才继续执行
            latch.await();
            System.out.println("两个任务执行完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("they are going home");
    }
}
